<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\controller\admin\AdminBaseController;
use think\Request;
use app\model\admin\SysRole as SysRoleModel;
use app\model\admin\SysDept as SysDeptModel;
use app\model\admin\SysUser;
use think\facade\Db;

class SysRole extends AdminBaseController
{

    public function index(Request $request)
    {
        $field = "*";
        $data = SysRoleModel::scope('where', $request->param())
            ->scope('dataFilter')
            ->field($field)
            ->order('id','desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        
        return successPage($data);
    }

    public function show(Request $request)
    {
        $id = $request->param('id');
        $data = SysRoleModel::where('id', $id)->scope('dataFilter')->find();

        if(!$data){
            return error('数据不存在');
        }
        return success($data);
    }

    public function save(Request $request)
    {
        $param = $request->param();
        if(isset($param['id'])){
            unset($param['id']);
        }
        
        $menuIds = $param['menuIds'] ?? [];
        if(empty($menuIds)){
            return error('请分配菜单权限');
        }
        Db::startTrans();
        $msg = 'success';
        try {
            $data = SysRoleModel::create($param);
            if($data->id > 0){
                $role_id = $data->id;
                Db::table('sys_role_menu')->where('role_id', $role_id)->delete();
                $add_datas = [];
                foreach ($menuIds as $menu_id){
                    $add_datas[] = [
                        'menu_id' => $menu_id,
                        'role_id' => $role_id,
                        // 'role_key' => $data['role_key']
                    ];
                }
                Db::table('sys_role_menu')->insertAll($add_datas);
            }
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([],"新增成功") : error($msg);
        
    }

    public function update(Request $request)
    {
        $param = $request->param();
        $menuIds = $param['menuIds'] ?? [];

        if(empty($menuIds)){
            return error('请分配菜单权限');
        }
        $id = $request->post('id');

        $role = SysRoleModel::where('id', $id)->scope('dataFilter')->find();
        if(!$role){
            return error('数据不存在');
        }

        Db::startTrans();
        $msg = 'success';
        try {
            $data = $request->only(['role_name','role_key','role_sort','status','remark']);
    
            $ret = $role->save($data);
            if($ret){
                $role_id = $id;
                Db::table('sys_role_menu')->where('role_id', $role_id)->delete();
                $add_datas = [];
                foreach ($menuIds as $menu_id){
                    $add_datas[] = [
                        'menu_id' => $menu_id,
                        'role_id' => $role_id,
                    ];
                }
                Db::table('sys_role_menu')->insertAll($add_datas);
            }
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([],"更新成功") : error($msg);
    }

    public function delete(Request $request)
    {
        $id = $request->param('id', '');
        if(!$id){
            return error('缺少必要参数');
        }
        
        $ids = explode(',', $id);

        Db::startTrans();
        $msg = 'success';
        try {
            $ret = SysRoleModel::destroy($ids);
            DB::table('sys_role_menu')->whereIn('role_id', $ids)->delete();
            DB::table('sys_role_dept')->whereIn('role_id', $ids)->delete();
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([],"删除成功") : error($msg);

    }

    public function dataScope(Request $request){
        $param = $request->post();
        $deptIds = $param['deptIds'] ?? [];
        $data_scope = $param['data_scope'];
        $role_id = $param['id'];

        $role = SysRoleModel::where('id', $role_id)->scope('dataFilter')->find();
        if(!$role){
            return error('数据不存在');
        }
        if($data_scope == 2 && empty($deptIds)){
            return error('请选择部门');
        }

        Db::startTrans();
        $msg = 'success';
        try {
            $data = $request->only(['data_scope']);
            $ret = $role->save($data);
            if($ret && count($deptIds) > 0){
                Db::table('sys_role_dept')->where('role_id', $role_id)->delete();
                $add_datas = [];
                foreach ($deptIds as $menu_id){
                    $add_datas[] = [
                        'dept_id' => $menu_id,
                        'role_id' => $role_id,
                    ];
                }
                Db::table('sys_role_dept')->insertAll($add_datas);
            }
            $result = true;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $result = false;
            $msg = $e->getMessage();
            // 回滚事务
            Db::rollback();
        }
        return $result ? success([],"更新成功") : error($msg);
    }
    // 根据角色ID查询部门树结构
    public function deptTree(Request $request){

        $role_id = $request->param('role_id', 0);
        $data = SysDeptModel::where('status', '1')->field('id,dept_name,parent_id,order_num')->select();
        $menus = makeTree($data->toArray(),'id', 'parent_id');
        $checkedKeys = Db::table('sys_role_dept')->where('role_id', $role_id)->column('dept_id');
        return success([
            'depts' => $menus,
            'checkedKeys' => $checkedKeys
        ]);
    }

    public function changeStatus(Request $request){
        $id = $request->param('id');
        $status = $request->param('status','');
        if(!$id || $status == ''){
            return error('缺少必要参数');
        }
        
        $model = SysRoleModel::where('id', $id)->scope('dataFilter')->find();

        $data = $request->only(['status']);
    
        $ret = $model->save($data);
        if(!$ret){
            return error('更新失败');
        }
        return success();
    }
    // 查询角色已授权用户列表
    public function allocatedList(Request $request){
        $role_id = $request->param('role_id', 0);
        //获取用户id
        $user_ids = Db::table('sys_user_role')->where('role_id', $role_id)->column('user_id');
        if(empty($user_ids)){
            return success();
        }
        //获取用户信息
        $field = "*";
        $data = SysUser::whereIn('id', $user_ids)->scope('where', $request->param())
            ->scope('dataFilter')
            ->field($field)
            ->order('id','desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        
         return successPage($data);

    }
    // 查询角色未授权用户列表
    public function unallocatedList(Request $request){
        $role_id = $request->param('role_id', 0);
        //获取用户id
        $user_ids = Db::table('sys_user_role')->where('role_id', $role_id)->column('user_id');
        
        //获取用户信息
        $field = "*";
        $data = SysUser::whereNotIn('id', $user_ids)->scope('where', $request->param())
            ->scope('dataFilter')
            ->field($field)
            ->order('id','desc')
            ->paginate([
                'list_rows' => $this->limit,
                'page' => $this->page,
                'var_page' => $this->pageVar
            ]);
        
         return successPage($data);
    }
    // 取消用户授权角色
    public function authUserCancel(Request $request){
        $role_id = $request->post('role_id', 0);
        $user_id = $request->post('user_id', 0);

        $ret = Db::table('sys_user_role')->where('role_id', $role_id)->where('user_id', $user_id)->delete();
        if(!$ret){
            return error('操作失败');
        }
        return success();
    }
    // 批量取消用户授权角色
    public function authUserCancelAll(Request $request){
        $role_id = $request->post('role_id', 0);
        $user_id = $request->post('user_id', '');

        $ids = explode(',', $user_id);
        $ret = Db::table('sys_user_role')->where('role_id', $role_id)->whereIn('user_id', $ids)->delete();
        if(!$ret){
            return error('操作失败');
        }
        return success();
    }

    // 授权用户选择
    public function authUserSelectAll(Request $request){
        $role_id = $request->post('role_id', 0);
        $user_ids = $request->post('user_ids', '');

        $ids = explode(',', $user_ids);

        $add_datas = [];
        foreach ($ids as $user_id){
            $add_datas[] = [
                'user_id' => $user_id,
                'role_id' => $role_id,
            ];
        }
        $ret = Db::table('sys_user_role')->insertAll($add_datas);
        if(!$ret){
            return error('操作失败');
        }
        return success();
    }

}
